/* eslint-disable */
/**
 * Created by GYL on 2018/8/24
 */
//事件模板管理
import React, { Component } from 'react';
import Filtrate from '../../components/common/Filtrate';
import Container from "../../components/common/Container";
import MyTable from "../../components/common/MyTable";
import PublicService from "../../services/PublicService";
import Add_Wrap from './sub/Add_Wrap';
import Edit_Wrap from './sub/Edit_Wrap';
import Check_Wrap from './sub/Check_Wrap';
import request from '../../utils/request';
import MyPagination from "../../components/common/MyPagination";
import { message, Icon, Drawer, Spin, Breadcrumb, Avatar } from 'antd';
import SubTask from './predecessors/SubTask';
import SubZS from './knowledgeBase/SubZS'; 
import moment from 'moment'
var treeArr = []
const IconFont = Icon.createFromIconfontCN({
  scriptUrl: '//at.alicdn.com/t/font_1315525_f8lqdqjh676.js',
});
class EventForm extends Component {

  state = {
    findKnowledgeBasedataSource: [],
    TaskArr: [],
    selectArr: [],
    SubTaskVisible: false,
    params: {},
    pageSize: 10,
    pageIndex: 1,
    total: 0,
    delConfirm: false,
    addModal: false,
    selectedRowKeys: [],
    dataSate: [],
    addWrap: false,
    editWrap: false,
    EditArr: [],
    AddArr: [],
    flag: true,
    tabData: {},
    Drawer_title: '知识库',
    eventBasicId: '',
    spinning: true,
    DownBoxOne:[]
  }
  componentDidMount() {
    this.getEventBasicInfoDropDownBox()
    this.onSubmit(1, 10)
    let params = {}
    request({
      url: '/pm-web/projectmanage/role/getTreeData',
      method: 'POST',
      data: { notManagementLayer: true }
    }).then(data => {
      if (data.rc === 0) {
        treeArr = data.ret
      }
    })

    this.dropDownBoxOne();
  }

  dropDownBoxOne = () => {
    request({
      url: '/pm-web/projectmanage/findData/dropDownBoxOne',
      method: 'GET',
    }).then(data => {
      this.setState({
        DownBoxOne:data.ret
      })
    })
  }

  getEventBasicInfoDropDownBox = () => {//事件上级下拉框请求
    request({
      url: '/pm-web/projectmanage/eventbasicinfo/getEventBasicInfoDropDownBox',
      method: 'POST',
      data: {}
    }).then(data => {
      // console.log(data)
      if (data.rc === 0) {
        let AddArr = []
        data.ret.forEach(item => {
          AddArr.push({ text: item.eventBasicName, value: item.eventBasicNumber })
        });

        this.setState({
          AddArr
        })
      }
    })
  }


  //查询
  onSubmit = (page, size) => {
    const params = this.f1.getForm().getFieldsValue();
    params.page = page;
    params.rows = size;

    this.setState({
      params,
      spinning: true,
      pageIndex: page,
      pageSize: size
    })

    request({
      url: '/pm-web/projectmanage/eventbasicinfo/findAllEventBasicInfo',
      method: 'POST',
      data: params
    }).then(data => {
      // console.log(data)
      if (data.rc === 0) {

        data.ret.ebiList.forEach((item) => {
          item.eventBasicStage = item.eventBasicStage == 1 ? '项目前期' : item.eventBasicStage == 2 ? '项目实施' : item.eventBasicStage == 3 ? '项目验收' : '项目结算'
          item.lastChangeTime = moment(item.lastChangeTime).format("YYYY-MM-DD HH:mm:ss")
          item.createTime = moment(item.createTime).format("YYYY-MM-DD HH:mm:ss")
        })

        this.setState({
          dataSate: data.ret.ebiList,
          sbiList: data.ret.sbiList,
          total: data.ret.rowCount,
          flag: data.ret.flag,
          spinning: false,
          selectedRowKeys: [],
        })
      }
    })
  }

  //重置
  ResetForm = () => {
    console.log('重置')
    this.setState({
      pageIndex: 1,
      pageSize: 10
    }, () => {
      this.onSubmit(1, 10)
    })
  }

  //新增
  addBtnText = () => {
    this.getEventBasicInfoDropDownBox()

    request({
      url: '/pm-web/projectmanage/button/judgeButtonIsOperation',
      method: 'POST',
      data: { userId: PublicService.getCookie('userId'), buttonName: '模板新增' }
    }).then(data => {
      if (data.rc === 0) {
        if (data.ret.type) {
          this.setState({
            addWrap: true
          })
        } else {
          message.warning('用户权限不足!')
        }
      }
    })

  }

  // 取消保存
  ModalCancel = (type) => {
    let t = this;
    t.setState({
      [type]: false,
      modalBtnLoading: false
    })
  };

  //多选
  onSelectChange = (selectedRowKeys, row) => {
    // console.log(selectedRowKeys, row)
    this.setState({ selectedRowKeys, row })
  };

  //编辑
  editBtn = (flag) => {
    this.getEventBasicInfoDropDownBox()
    if (this.state.selectedRowKeys.length !== 1) {
      message.warning('只能对单一事件编辑!')
      return
    }

    request({
      url: '/pm-web/projectmanage/eventbasicinfo/getEventBasicInfoDropDownBox',
      method: 'POST',
      data: { eventBasicId: this.state.dataSate[this.state.selectedRowKeys[0]].eventBasicId }
    }).then(data => {
      if (data.rc === 0) {
        let AddArr = []
        data.ret.forEach(item => {
          AddArr.push(
            { text: item.eventBasicName, value: item.eventBasicNumber }
          )
        });
        PublicService.setCookie('eventBasicId', this.state.dataSate[this.state.selectedRowKeys[0]].eventBasicId);
        this.setState({
          AddArr,
          eventBasicId: this.state.dataSate[this.state.selectedRowKeys[0]].eventBasicId
        })
      }
    })

    let params = {}


    request({
      url: '/pm-web/projectmanage/eventbasicinfo/findOneEventBasicInfo',
      method: 'POST',
      data: { eventBasicId: this.state.dataSate[this.state.selectedRowKeys[0]].eventBasicId }
    }).then(data => {
      // console.log(data)
      if (data.rc === 0) {
        data.ret.treeArr = treeArr
        this.setState({
          warpFlag: flag,
          EditArr: data.ret,
        })

        if (flag) {//flag=true 编辑操作  false查看操作
          request({
            url: '/pm-web/projectmanage/button/judgeButtonIsOperation',//查询是否具有权限
            method: 'POST',
            data: { userId: PublicService.getCookie('userId'), buttonName: '模板修改' }
          }).then(data => {
            if (data.rc === 0) {
              if (data.ret.type) {
                this.setState({
                  editWrap: true,//打开编辑图层
                })
              } else {
                message.warning('用户权限不足!')

              }
            }
          })

        } else {
          this.setState({
            checkWrap: true,//打开查看图层
          })
        }



      }
    })
  }



  // 分页
  onChangePage = (page, size) => {
    this.setTimeAndSearch(this.state.params, page, size);
    this.setState({
      pageSize: size,
      pageIndex: page,
    })
  };

  onChangePage1 = (page, size) => {

    this.setTimeAndSearch(this.state.params, 1, size);
    this.setState({
      pageSize: size,
      pageIndex: 1,
    })
  };

  setTimeAndSearch = (val, pageIndex, row) => {
    this.setState({
      spinning: true,
      pageIndex,
      pageSize: row
    })


    val.page = pageIndex;
    val.rows = row;
    this.state.params.isField = this.state.Radio ? 0 : ""
    request({
      url: '/pm-web/projectmanage/eventbasicinfo/findAllEventBasicInfo',
      method: 'POST',
      data: val
    }).then(data => {
      if (data.rc === 0) {
        data.ret.ebiList.forEach((item) => {
          item.eventBasicStage = item.eventBasicStage == 1 ? '项目前期' : item.eventBasicStage == 2 ? '项目实施' : item.eventBasicStage == 3 ? '项目验收' : '项目结算'
          item.lastChangeTime = moment(item.lastChangeTime).format("YYYY-MM-DD HH:mm:ss")
          item.createTime = moment(item.createTime).format("YYYY-MM-DD HH:mm:ss")
        })

        this.setState({
          dataSate: data.ret.ebiList,
          sbiList: data.ret.sbiList,
          total: data.ret.rowCount,
          flag: this.state.flag,
          spinning: false,
          selectedRowKeys: [],
        })
      }
    })

  };


  //上移
  UPBtn = (text, record, index) => {
    request({
      url: '/pm-web/projectmanage/button/judgeButtonIsOperation',//查询是否具有权限
      method: 'POST',
      data: { userId: PublicService.getCookie('userId'), buttonName: '上移下移' }
    }).then(data => {
      if (data.rc === 0) {
        if (data.ret.type) {
          if (record.num === 1) {
            return
          }
          if (!this.state.flag) {
            return
          }
          request({
            url: '/pm-web/projectmanage/eventbasicinfo/updateEventBasicNumber',
            method: 'POST',
            data: { eventBasicId: record.eventBasicId, direction: 'up' }
          }).then(data => {
            if (data.rc === 0) {
              message.success("上移成功!")
              this.setTimeAndSearch(this.state.params, this.state.params.page, this.state.params.rows);
            } else {
              message.warning("移动失败")
            }
          })
        } else {
          message.warning("用户权限不足!")
        }
      }
    })

  }


  //下移
  DownBtn = (text, record, index) => {
    request({
      url: '/pm-web/projectmanage/button/judgeButtonIsOperation',//查询是否具有权限
      method: 'POST',
      data: { userId: PublicService.getCookie('userId'), buttonName: '上移下移' }
    }).then(data => {
      if (data.rc === 0) {
        if (data.ret.type) {
          if (record.num === this.state.total) {
            return
          }
          if (!this.state.flag) {
            return
          }
          request({
            url: '/pm-web/projectmanage/eventbasicinfo/updateEventBasicNumber',
            method: 'POST',
            data: { eventBasicId: record.eventBasicId, direction: 'below' }
          }).then(data => {
            if (data.rc === 0) {
              message.success("下移成功!")
              let params = this.state.params

              this.setTimeAndSearch(this.state.params, this.state.params.page, this.state.params.rows);
            } else {
              message.warning("移动失败")
            }
          })
        } else {
          message.warning("用户权限不足!")
        }
      }
    })


  }

  // 删除对话框
  setDelConfirm = () => {
    if (this.state.selectedRowKeys.length === 0) {
      message.warning("请选择要删除事件");
    } else {
      this.setState({
        delConfirm: true,
      });
    }
  };
  //取消删除
  deleteBtnCancel = () => {
    this.setState({
      delConfirm: false,
    });
  };
  //删除
  onDelete = () => {
    this.getEventBasicInfoDropDownBox()
    request({
      url: '/pm-web/projectmanage/button/judgeButtonIsOperation',//查询是否具有权限
      method: 'POST',
      data: { userId: PublicService.getCookie('userId'), buttonName: '模板删除' }
    }).then(data => {
      if (data.rc === 0) {
        if (data.ret.type) {
          let t = this;
          let params = []

          this.state.row.forEach((item) => {
            params.push({
              eventBasicId: item.eventBasicId
            })
          })

          request({
            url: '/pm-web/projectmanage/eventbasicinfo/deleteEventBasicInfo',
            method: 'POST',
            data: params
          }).then(data => {
            if (data.rc === 0) {
              message.success("删除成功");
              this.onSubmit(1, 10)
              this.setState({
                delConfirm: false,
                selectedRowKeys: [],
              });
            } else {
              message.error(data.err)
            }
          })
        } else {
          message.warning('用户权限不足!')

        }
      }
    })


  };
  //前置任务
  TaskBtn = (text, record, index) => {
    request({
      url: '/pm-web/projectmanage/button/judgeButtonIsOperation',//查询是否具有权限
      method: 'POST',
      data: { userId: PublicService.getCookie('userId'), buttonName: '模板删除' }
    }).then(data => {
      if (data.rc === 0) {
        if (data.ret.type) {
          //查询子事件任务下拉
          request({
            url: '/pm-web/projectmanage/preposetaskbasic/getSubeventsBasicInfoDropDownBox',
            method: 'POST',
            data: { eventBasicId: record.eventBasicId, subeventsBasicId: record.subeventsBasicId }
          }).then(data => {
            // console.log(data)
            if (data.rc === 0) {
              this.setState({
                selectArr: data.ret
              })
            }
          })
          //查询前置任务
          request({
            url: '/pm-web/projectmanage/preposetaskbasic/findPreposeTaskBasic',
            method: 'POST',
            data: { subeventsBasicId: record.subeventsBasicId }
          }).then(data => {
            // console.log(data)
            this.setState({
              record: record,
              TaskArr: data.ret,
              SubTaskVisible: true,
            })
          })

        } else {
          message.warning('用户权限不足!')

        }
      }
    })

  }

  onModalSave = () => {
    this.setState({
      SubTaskVisible: false
    })

  }

  fanhui = (v) => {
    this.setState({
      [v]: false,
      selectedRowKeys: [],
      row: [],
      pageSize: 10,
      pageIndex: 1
    })
    this.onSubmit(1, 10)
  }


  onKnowledgebase = (record) => {

    request({
      url: '/pm-web/projectmanage/button/judgeButtonIsOperation',//查询是否具有权限
      method: 'POST',
      data: { userId: PublicService.getCookie('userId'), buttonName: '模板删除' }
    }).then(data => {
      if (data.rc === 0) {
        if (data.ret.type) {
          this.setState({
            Drawer_title: record.eventBasicName,
            eventBasicId: record.eventBasicId
          })
          let params = {
            eventBasicId: record.eventBasicId,
            page: 1,
            rows: 99999
          }
          request({
            url: `/pm-web/projectmanage/knowledgebase/findKnowledgeBase`,
            method: 'POST',
            data: params
          }).then(data => {
            // console.log(data)
            if (data.rc === 0) {
              this.setState({
                findKnowledgeBasedataSource: data.ret.list
              })
              this.showDrawer()
            }
          })
        } else {
          message.warning('用户权限不足!')
        }
      }
    })


  }

  showDrawer = () => {
    this.setState({
      visible: true,
    });
  };

  onClose = () => {
    this.setState({
      visible: false,
    });
    this.onSubmit(1, 10)

  };

  render() {

    let width = document.body.clientWidth;
    const height = document.body.clientHeight;
    let containerHeight = '83vh';
    let autoCompleteWidth = 340
    let tableHeight = 280;
    if (width < 1920) {
      tableHeight = 280;
      containerHeight = '76vh';
      autoCompleteWidth = 540
    }
    const { pageSize, pageIndex, selectedRowKeys, total, dataSate, delConfirm } = this.state
    let rowSelection = {
      selectedRowKeys,
      onChange: this.onSelectChange.bind(this),
    };
    const DrawerTitle = (
      <div>
        <Breadcrumb>
          <Breadcrumb.Item >
            <IconFont type="icon-moban" style={{ color: '#28a4b9' }} />
            <span>事件模板管理</span>
          </Breadcrumb.Item>
          <Breadcrumb.Item>
            <IconFont type="icon-zhishi" style={{ color: 'rgb(109, 103, 229)' }} />
            <span>知识库信息</span>
          </Breadcrumb.Item>

        </Breadcrumb>
      </div>
    )
    const {DownBoxOne} = this.state;

    const items = [
      {
        type: 'autoComplete',
        label: '事件名称',
        placeholder: '请输入 ..',
        paramName: 'eventBasicName',
        width:autoCompleteWidth,
        options:DownBoxOne
      },
      {
        type: 'select',
        label: '事件阶段',
        paramName: 'eventBasicStage',
        options: [
          { text: '全部', value: '' },
          { text: '项目前期', value: '1' },
          { text: '项目实施', value: '2' },
          { text: '项目验收', value: '3' },
          { text: '项目结算', value: '4' },

        ],
      },
    ];

    const columns = [
      { title: '序号', dataIndex: 'num', width: 50 },
      { title: '事件阶段', dataIndex: 'eventBasicStage', key: 'platform', width: 100 },
      {
        title: '事件名称', dataIndex: 'eventBasicName', key: 'name', width: 200,
        render: (text, record, index) => <span>
          <span>{record.eventBasicNameArr[0]}</span><span style={{ color: 'red' }}>{record.eventBasicNameArr[1]}</span><span>{record.eventBasicNameArr[2]}</span>

        </span>
      },
      { title: '创建人员', dataIndex: 'creatorName', key: 'upgradeNum', width: 100 },
      { title: '创建时间', dataIndex: 'createTime', key: 'creator', width: 120 },
      { title: '编辑人员', dataIndex: 'lastChangerName', key: 'createdAt', width: 120 },
      { title: '编辑时间', dataIndex: 'lastChangeTime', width: 120 },
      {
        title: '知识库', key: 'knowledgebase', width: 100, render: (text, record, index) => <span onClick={this.onKnowledgebase.bind(this, record)}>
          <IconFont type="icon-zhishi" style={{ color: '#28a4b9', cursor: 'pointer', fontSize: 34 }} />
        </span>
      },
      {
        title: '操作', key: 'operation', width: 100, render: (text, record, index) => <span>

          {/* <a href="javascript:;" onClick={this.UPBtn.bind(this, text, record, index)}>上移</a> */}
          <IconFont type="icon-shangyi" onClick={this.UPBtn.bind(this, text, record, index)} style={{ fontSize: 20, cursor: 'pointer', width: 20, height: 20, color: record.num === 1 ? '#ccc' : this.state.flag ? '#16B8BD' : '#ccc' }} />
          {/* <a style={{ marginLeft: 5 }} href="javascript:;" onClick={this.DownBtn.bind(this, text, record, index)}>下移</a> */}
          <IconFont type="icon-xiayi2" onClick={this.DownBtn.bind(this, text, record, index)} style={{ fontSize: 20, cursor: 'pointer', width: 20, height: 20, color: record.num == this.state.total ? '#ccc' : this.state.flag ? 'red' : '#ccc' }} />


        </span>
      },
    ];



    const expandedRowRender = (record, index, indent, expanded) => {
      let columns = [
        {
          title: '子事件名称', dataIndex: 'subeventsBasicName', key: 'subeventsBasicName',
          render: (text, record, index) => <span>
            <span>{record.subeventsBasicNameArr[0]}</span><span style={{ color: 'red' }}>{record.subeventsBasicNameArr[1]}</span><span>{record.subeventsBasicNameArr[2]}</span>

          </span>
        },
        { title: '权重', dataIndex: 'subeventsBasicWeight', key: 'subeventsBasicWeight' },
        {
          title: '关联任务', key: 'operation', width: 100, render: (text, record, index) => <span>
            <a style={{ marginLeft: 5 }} href="javascript:;" onClick={this.TaskBtn.bind(this, text, record, index)}>编辑</a>

          </span>
        },
      ];

      return <MyTable columns={columns} dataSource={this.state.sbiList[index]} pagination={false} />;
    };
    return (
      <div style={{ position: 'relative', boxSize: 'border-box', padding: 5, paddingTop: 0, height: '90vh' }}>
        {/* 新增页面 */}
        {
          this.state.addWrap &&
          <Add_Wrap
            AddArr={this.state.AddArr}
            fanhui={this.fanhui.bind(this, 'addWrap')}
          />

        }
        {/* 编辑页面 */}
        {
          this.state.editWrap &&
          <Edit_Wrap
            EditArr={this.state.EditArr}
            AddArr={this.state.AddArr}
            fanhui={this.fanhui.bind(this, 'editWrap')}
            eventBasicId={this.state.eventBasicId}
          />

        }
        {/* 查看页面 */}
        {
          this.state.checkWrap &&
          <Check_Wrap
            EditArr={this.state.EditArr}
            AddArr={this.state.AddArr}
            fanhui={this.fanhui.bind(this, 'checkWrap')}
            eventBasicId={this.state.eventBasicId}
          />

        }

        {
          this.state.SubTaskVisible &&
          <SubTask
            mask={true}
            width={1400}
            visible={this.state.SubTaskVisible}
            title={`编辑${this.state.record.subeventsBasicName}前置任务`}
            footerShow={true}
            destroyOnClose={true}
            onCancel={this.ModalCancel.bind(this, 'SubTaskVisible')}
            onModalSave={this.onModalSave}
            footerTitle={'确定'}
            TaskArr={this.state.TaskArr}
            selectArr={this.state.selectArr}
            record={this.state.record}
          />
        }
        <Drawer
          title={DrawerTitle}
          placement="right"
          closable={false}
          onClose={this.onClose}
          visible={this.state.visible}
          width={800}
          bodyStyle={{ height: '80%' }}
          destroyOnClose={true}
        >
          <SubZS findKnowledgeBasedataSource={this.state.findKnowledgeBasedataSource} tabData={this.state.tabData} eventBasicId={this.state.eventBasicId} />
        </Drawer>
        <Spin spinning={this.state.spinning} size='large'>
          <Filtrate
            items={items}
            ref={ref => { this.f1 = ref }}
            submit={this.onSubmit.bind(this, 1, 10)}
            ResetForm={this.ResetForm}
          />

          <Container
            style={{ height: containerHeight, position: "relative", overflow: 'auto' }}
            // exportBtnShow={true}
            // exportBtn={this.exportBtn}
            delConfirm={delConfirm}
            addBtnText={this.addBtnText.bind(this, "新增")}
            deleteBtnCancel={this.deleteBtnCancel.bind(this)}
            examineBtn={this.editBtn.bind(this, false)}
            editBtn={this.editBtn.bind(this, true)}
            lockBtn={this.lockBtn}
            clearlockBtn={this.clearlockBtn}
            setDelConfirm={this.setDelConfirm}
            addBtnShow={true}
            deleteBtnShow={true}
            editBtnShow={true}
            deleteBtn={this.onDelete.bind(this)}
            // UPBtnShow={true}
            // UPBtn={this.UPBtn}
            // DownBtnShow={true}
            // DownBtn={this.DownBtn}
            examineBtnShow={true}
          // lockBtnShow={true}
          // clearlockBtnShow={true}
          >

            <MyTable

              columns={columns}
              rowSelection={rowSelection}
              expandedRowRender={expandedRowRender}
              scroll={{ y: height - tableHeight }}
              dataSource={PublicService.transformArrayData(dataSate, true, true, pageIndex, pageSize)}
              pagination={false}
            />
            <MyPagination
              showPage
              pageSize={pageSize}
              current={this.state.pageIndex}
              total={total}
              showSizeChanger
              showQuickJumper
              onChange={this.onChangePage.bind(this)}
              onShowSizeChange={this.onChangePage1.bind(this)}
            />




          </Container>
        </Spin>
      </div>
    );


  }
}
export default EventForm;

